#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h> 
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#define SERVER_IP "192.168.62.129"  //服务器IP地址
#define SERVER_PORT 1234
#define BUFFER_SIZE 1024
#define RECV_SERVER_PATH "./recv_server_text/"  //服务器接收客户端文件夹路径
#define SEND_SERVER_PATH "./send_server_text/"   //服务器发送文件夹路径
#define FILES_NAME "欢迎查询服务端文件系统,服务端文件表名分别为：1，2，3，4，5，6，7" //服务端文件表名

int init_Server(int port)
{
  int serverSocket;
  struct sockaddr_in server_addr;
  // socket初始化
  if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    perror("socket");
    return -1;
  }
  //服务端地址类型，地址及端口初始化
  bzero(&server_addr, sizeof(server_addr));
  server_addr.sin_family = AF_INET;
  server_addr.sin_port = htons(port);
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  if (bind(serverSocket, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
  {
    perror("connect");
    return -1;
  }
  //设置服务器上的socket为监听状态
  if (listen(serverSocket, 5) < 0)
  {
    perror("listen");
    return -1;
  }
  return serverSocket;
}

int get_File_Num(char *pathname)
{
  struct dirent *ptr;
  DIR *path = NULL;
  path = opendir(pathname);
  int cnt = 0;
  while ((ptr = readdir(path)) != NULL)
  {
    if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
      continue;
    if (ptr->d_type == DT_REG)
      cnt++;
  }
  return cnt;
}

int pack_send_File(int Socket, FILE* fp) {
  char send_buf[BUFFER_SIZE] = {0};
  int len_file, len_block;
  int totalBlock;
  fseek(fp,0,2);//将指针放到文件末尾
  len_file = ftell(fp); //统计文本的数据长度
  rewind(fp); //让指针指向文件开始位置
  printf("文件的总长度len_file:%d\n",len_file);
  totalBlock = len_file % BUFFER_SIZE == 0 ? len_file / BUFFER_SIZE : ((len_file / BUFFER_SIZE) + 1); //除最后一快的总块数
  printf("文件的总块数totalBlock:%d\n",totalBlock);
  sprintf(send_buf, "%d", totalBlock);
  send(Socket,(char*)send_buf,sizeof(send_buf),0);
  for(int i = 1; i <= totalBlock; i++) {
    len_block = fread(send_buf, 1, BUFFER_SIZE, fp);
    send_buf[len_block]='\0';
    char temp[100] = {0};
    sprintf(temp, "%d", len_block);
    printf("文件第%d块的长度len_block:%s\n",i,temp);
    send(Socket,(char*)temp,sizeof(temp),0);
    printf("第%d块的内容:%s\n",i,send_buf);
    send(Socket,send_buf,len_block,0);
  }
  fclose(fp);
}

int receive_File(int clientSocket)
{
  char recv_buf[BUFFER_SIZE] = {0};
  char filename[200] = {0}, pathname[200] = {0};
  int cnt;
  int totalBlock, lenBlock;
  recv(clientSocket, recv_buf, sizeof(recv_buf), 0); //先接收客户端要传多少个文件
  // printf("%d\n",(int)strlen(recv_buf));
  int filenum = atoi(recv_buf);
  printf("客户端要发送%d个文件\n", filenum);
  for (int i = 1; i <= filenum; i++)
  {
    //遍历指定目录下文件的个数，以确定新接收文件的名字
    cnt = get_File_Num((char *)RECV_SERVER_PATH); //得到服务器目录下的文件个数，方便编号命名
    FILE *fp;
    memset(filename, 0, sizeof(filename));
    sprintf(filename, "%d", cnt + 1);
    strcpy(pathname, RECV_SERVER_PATH);
    strcat(pathname, filename);
    printf("%s\n", pathname);
    fp = fopen(pathname, "wb");
    if (fp != NULL)
      printf("成功创建文件%s\n", pathname);
    recv(clientSocket, recv_buf, sizeof(recv_buf), 0);
    totalBlock = atoi(recv_buf);
    // printf("第%d个文件有%d个块\n", i, totalBlock);
    for (int j = 1; j <= totalBlock; j++)
    {
      char temp[100] = {0};
      recv(clientSocket, temp, sizeof(temp), 0);
      lenBlock = atoi(temp);
      // printf("第%d个块长度为%d\n", j, lenBlock);
      if ((recv(clientSocket, recv_buf, lenBlock, 0)) != -1){
        // printf("..........接收成功..........\n");
      }
      else{
        printf("接收失败!\n");
        break;
      }
      fwrite(recv_buf, 1, lenBlock, fp);
    }
    fclose(fp);
    char *p = (char *)"文件保存完毕";
    printf("%s\n\n", p);
  }
  // close(clientSocket);
}

int submit_File(int Socket, char* filename) {//提交单个文件
  //将文件内容发送给客户端
  FILE *fp;
  char send_buf[BUFFER_SIZE] = {0};
  char* pre_filename = (char*)malloc(sizeof(char)*100);
  strcpy(pre_filename,SEND_SERVER_PATH);
  strcat(pre_filename,filename);
  fp = fopen(pre_filename, "rb");
  if(fp == NULL) {
    printf("文件不存在，请客户端重新输入！\n");
  }else{
    printf("已找到文件");
    pack_send_File(Socket, fp);
    printf("文件上传成功！\n");
  }
  // close(Socket);
}

void KKL_Implement() {}

void choose(int ch, int socket){
  switch (ch)
	{
	case 1: //向服务端发送文件
    //将客户端发送过来的消息写入文件
    receive_File(socket);
    KKL_Implement(); //实现服务器端KKL协议的接口
    close(socket);
		break;
	case 2: //获取服务端文件表名
    {
      char *data = FILES_NAME;
      write(socket, data , strlen(data));
      close(socket);
      break;
    }
  case 3: //从服务端下载文件
    {
      //获取客户端想要下载的文件名
      char filename[100] = {0};
      int len = read(socket, filename, sizeof(filename));
      if(len == -1){
          printf("获取download文件表名失败");
      }else if(len > 0){
          printf("recv client data : %s\n", filename);
      }
      //传输客户端想要的文件
      submit_File(socket, filename);
      close(socket);
      break;
    }
	default: printf("Input error!\n");
	}

}

int main()
{
  FILE *fp;
  int serverSocket;
  struct sockaddr_in clientAddr;
  int addr_len = sizeof(clientAddr);
  int clientSocket;
  // char send_buf[BUFFER_SIZE] = {0}, recv_buf[BUFFER_SIZE] = {0};
  // int iDataNum;

  serverSocket = init_Server(SERVER_PORT);
  if (serverSocket < 0)
  {
    printf("服务器初始化失败！\n");
    return 0;
  }
  printf("服务器初始化成功，监听端口：%d\n", SERVER_PORT);
  //等待用户连接
  while (1)
  {
    clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, (socklen_t *)&addr_len);
    if (clientSocket < 0)
    {
      printf("服务端accept失败，程序退出。\n");
      return 0;
    }

    printf("客户已连接：\n");
    printf("IP is %s\n", inet_ntoa(clientAddr.sin_addr)); // inet_ntoa ip地址转换函数，将网络字节序IP转换为点分十进制IP
    printf("Port is %d\n", htons(clientAddr.sin_port));
    printf("等待消息...\n");

    //解析客户端的需求类型
    char recv_type[BUFFER_SIZE] = {0} ;
    recv(clientSocket, recv_type, sizeof(recv_type), 0); //客户端的需求是1，2，3？
    int tpye = atoi(recv_type);
    printf("客户端的需求是: %d\n", tpye);
    choose(tpye, clientSocket);



    
  }
  
  // clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddr, (socklen_t *)&addr_len);
  // if (clientSocket < 0)
  // {
  //   printf("服务端accept失败，程序退出。\n");
  //   return 0;
  // }

  // printf("客户已连接：\n");
  // printf("IP is %s\n", inet_ntoa(clientAddr.sin_addr)); // inet_ntoa ip地址转换函数，将网络字节序IP转换为点分十进制IP
  // printf("Port is %d\n", htons(clientAddr.sin_port));
  // printf("等待消息...\n");



  // //将客户端发送过来的消息写入文件
  // receive_File(clientSocket);
  // KKL_Implement(); //实现服务器端KKL协议的接口
  close(serverSocket);
  return 0;
}


